package com.interview.c_死锁.b_多人同时转账;

import com.interview.c_死锁.a_转账.Account;
import com.interview.c_死锁.a_转账.Transfer;

import java.util.Random;

/**
 * 多人同时转账
 * <p>
 * * 死锁的四个条件
 * * 1.互斥
 * * 2.保持并请求
 * * 3.不可取消
 * * 4.形成闭环
 */
public class Test {
    static Random random = new Random();
    static Account[] accounts;

    public synchronized static void main(String[] args) {

        //准备可能转账的人群 一共1000人
        accounts = new Account[1000];
        for (int i = 0; i < 1000; i++) {
            accounts[i] = new Account(i + "", random.nextInt(1000));
        }

        //模拟500人 同时操作
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    Account from = accounts[random.nextInt(1000)];
                    Account to = accounts[random.nextInt(1000)];
                    Transfer.transferMoney(from, to, 500);
                }
            }).start();
        }

    }
}

